package com.bbm.communitysystem.filter;

import com.bbm.communitysystem.core.Token;
import com.bbm.communitysystem.core.filter.Verify;
import com.bbm.communitysystem.core.redis.PerRedis;
import com.bbm.communitysystem.core.redis.RoleRedis;
import com.bbm.communitysystem.domain.Per;
import com.bbm.communitysystem.domain.Role;
import com.bbm.communitysystem.domain.UserInfo;
import com.bbm.communitysystem.domain.dto.UserCredDto;
import com.bbm.communitysystem.service.IUserInfoService;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * api过滤器
 */
@Slf4j
//@Component
@RequiredArgsConstructor
public class PerFilter implements Filter, Ordered {

    private final PerRedis perRedis;

    private final IUserInfoService userInfoService;

    private final RoleRedis roleRedis;

    private final Token token;

    private final Verify verify;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (verify.verifyAdmin(request)) {
            filterChain.doFilter(servletRequest, response);
            return;
        }

        if (verify.verifyError(request)) {
            filterChain.doFilter(servletRequest, response);
            return;
        }


        Per value = perRedis.getValue(request.getServletPath());


        if (value != null) {

            UserCredDto userCredDto = token.parseToken(request.getHeader("auth"));
            Integer id = userCredDto.getId();

            UserInfo userInfo = userInfoService.getById(id);

            Role role = roleRedis.getRole(userInfo.getUserRoleId());

            if (role == null) {
                response.sendError(50000, "普通用户 无法访问该业务");
                filterChain.doFilter(servletRequest, response);
                return;
            }

            if (role.getRoleName().equals("admin")) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }

            String[] perIds = role.getRolePerId().split(",");


            for (String perId : perIds) {
                if (perId.equals(value.getId() + "")) {
                    filterChain.doFilter(servletRequest, response);
                    return;
                }
            }

            response.setStatus(404);

            filterChain.doFilter(servletRequest, response);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public int getOrder() {
        return 101;
    }
}
